﻿using ch341aSPIHelperDebugger;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class spihelper : Form
    {
        public spihelper()
        {
            InitializeComponent();
            LIST_Box.SelectedIndex = 1;
            Child_window_hide_already = false;
            Child_Gamma_Window_Open_Enable = true;
        }
        spihelper frm_main = null;
        eDP_Setting eDP_Setting_Form = null;
        private eDP_Setting frmaeDP_Setting = null;
        public bool Child_Gamma_Window_Open_Enable = true;
        public bool Child_window_hide_already = false;

        bool READ_ACK = false;
        long DLL_Version = 0;
        long Drv_Version = 0;
        long IC_Version = 0;
        int Device_ID = 0;
        public bool Device_status = false;

        //for more information about native lib,please check the CH341DLL.h file
        [DllImport("CH341DLL.DLL")]
        public static extern bool CH341StreamSPI4(int index, int iChipSelect, int iLength, byte[] buf);
        
        //[DllImport("CH341DLL.DLL")]
        //// 获取CH341芯片的版本,返回:0=设备无效,0x10=CH341,0x20=CH341A
        //public static extern long CH341GetVerIC(int iIndex);  // 指定CH341设备序号

        [DllImport("CH341DLL.DLL")]
        public static extern bool CH341SetStream(int index, int m);

        [DllImport("CH341DLL.DLL")]
        public static extern bool CH341OpenDevice(int index);

        [DllImport("CH341DLL.DLL")]
        public static extern void CH341CloseDevice(int index);

        [DllImport("CH341DLL.DLL")]
        public static extern bool CH341ReadI2C(  // 从I2C接口读取一个字节数据
        int iIndex,  // 指定CH341设备序号
        byte iDevice,  // 低7位指定I2C设备地址
        byte iAddr,  // 指定数据单元的地址
        byte[] oByte);  // 指向一个字节单元,用于保存读取的字节数据

        [DllImport("CH341DLL.DLL")]
        public static extern bool CH341WriteI2C(  // 向I2C接口写入一个字节数据
        int iIndex,  // 指定CH341设备序号
        byte iDevice,  // 低7位指定I2C设备地址
        byte iAddr,  // 指定数据单元的地址
        byte iByte);  // 待写入的字节数据

        [DllImport("CH341DLL.DLL")]
        public static extern long CH341GetVersion();  // 获得DLL版本号,返回版本号

        [DllImport("CH341DLL.DLL")]
        public static extern long  CH341GetDrvVersion();  // 获得驱动程序版本号,返回版本号,出错则返回0


        [DllImport("CH341DLL.DLL")]
        public static extern bool CH341SetDelaymS(  // 设置硬件异步延时,调用后很快返回,而在下一个流操作之前延时指定毫秒数
        long iIndex,  // 指定CH341设备序号
        long iDelay);  // 指定延时的毫秒数

        [DllImport("CH341DLL.DLL")]
        public static extern long CH341GetVerIC(  // 获取CH341芯片的版本,返回:0=设备无效,0x10=CH341,0x20=CH341A
        long iIndex);  // 指定CH341设备序号
                       //#define		IC_VER_CH341A		0x20;
                       //#define		IC_VER_CH341A3		0x30;













        //public void IIC_communication_BY_USB(byte device, byte slave_address, byte reg_address, byte reg_data);



        private byte[] strToToHexByte(string str_temp)
        {
            string hexString = "";
            hexString = str_temp;
            try {
                hexString = hexString.Replace(" ", "");
                hexString = hexString.Replace("\r", "");
                hexString = hexString.Replace("\n", "");
                if ((hexString.Length % 2) != 0)
                    hexString += "0";
                byte[] returnBytes = new byte[hexString.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                return returnBytes;
            }
            catch(FormatException e)
            {
                MessageBox.Show("illegal hex value");
                return null;
            }
        }
        public string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2")+" ";
                }
            }
            return returnStr;
        }

        private void open341_Click(object sender, EventArgs e)
        {
            if (CH341OpenDevice(Device_ID) &&CH341SetStream(0, 0x81))
            {
                Message.Text = "Ch341A is ready!";
                open341.Enabled = false;
                close341.Enabled = true;
                //datalen.Enabled = true;
                formatdw.Enabled = true;
                dataw.Enabled = true;
                datar.Enabled = true;
                transport.Enabled = true;
                //datalen.Enabled = true;
                claerdataw.Enabled = true;
                cleardatar.Enabled = true;
                //IC_Version = CH341GetVerIC(Device_ID);
                //if (READ_ACK = true)
                {
                    DLL_Version = CH341GetVersion();
                    Drv_Version = CH341GetDrvVersion();
                    //IC_Version = CH341GetVerIC(Device_ID);
                }
                Device_status = true;
            }
            else
            {
                Message.Text = "Ch341A is not ready,cheak your deriver and hardware";
            }
            
        }

        public byte IIC_communication_BY_USB(byte device, byte slave_address, byte reg_address, byte reg_data)
        {
            //int lenth = int.Parse(datalen.Text);
            Message.Text = "传输开始>>>>>>>>>   ";
            Application.DoEvents();//重点，必须加上，UI更新
            //byte[] wbuff = strToToHexByte(dataw.Text);
            //if (wbuff == null) return;/////输入数据为空时，跳出函数。
            //int lenth = wbuff.Length;
            byte[] read_data = { 0 };
            //datalen.Text = Convert.ToString(lenth);

            //byte[] rbuff = new byte[lenth];
            //for (int i = 0; i < wbuff.Length; i++)
            //{
            //    if (rbuff.Length > i) rbuff[i] = wbuff[i];
            //}

            READ_ACK = false;
            switch (LIST_Box.SelectedIndex)
            {
                case 0://////进入SPI模式传输code，
                //    READ_ACK = CH341StreamSPI4(Device_ID, 0x80, lenth, rbuff);
                    break;

                case 1:
                    //if (wbuff.Length % 3 != 0) { break; }
                    //for (int i = 0; i < wbuff.Length / 3; i++)
                    {
                        if ((slave_address % 2) == 0)
                        {
                            ////写入函数
                            /////按照IIC格式，device address，reg  address ，data进行传送。  设备地址此处兼容8805代码，从8bit缩减为7bit模式进行传输。
                            READ_ACK = CH341WriteI2C(device, Convert.ToByte(slave_address / 2), reg_address, reg_data);
                        }
                        else
                        {
                            ////回读函数 
                            READ_ACK = CH341ReadI2C(device, Convert.ToByte(slave_address / 2), reg_address, read_data);
                            reg_data = read_data[0];
                        }
                        //progressBar1.Value = i * 100 / (wbuff.Length / 3);////显示送code的进度条
                                                                          //CH341SetDelaymS(0, 1);/////延时api无效。


                    }
                    break;

                default:
                  //  READ_ACK = CH341StreamSPI4(Device_ID, 0x80, lenth, rbuff);
                    break;
            }


            //for(int i=0;i< lenth;i++)
            //{
            //    datar.Text = byteToHexStr(rbuff);
            //}
           // progressBar1.Value = 100;////显示送code的进度条 100%完成；
            Message.Text = "传输完成>>>>>>>>>      ";

            return reg_data;
           // countDataw.Text = "共计传输了: " + wbuff.Length / 3 + " 笔";
            //formatDataw
        }

        private void transport_Click(object sender, EventArgs e)
        {
            //int lenth = int.Parse(datalen.Text);
            Message.Text = "传输开始>>>>>>>>>   ";
            Application.DoEvents();//重点，必须加上，UI更新
            byte[] wbuff = strToToHexByte(dataw.Text);
            if (wbuff == null) return;/////输入数据为空时，跳出函数。
            int lenth = wbuff.Length;
            byte[] read_data= { 0};
            datalen.Text = Convert.ToString(lenth);
            
            byte[] rbuff = new byte[lenth];
            for (int i = 0; i < wbuff.Length; i++)
            {
                if(rbuff.Length>i)rbuff[i] = wbuff[i];
            }
            
            READ_ACK = false;
            switch(LIST_Box.SelectedIndex)
                { 
                case 0://////进入SPI模式传输code，
                    READ_ACK = CH341StreamSPI4(Device_ID, 0x80, lenth, rbuff);
                    break;

                case 1:
                    if (wbuff.Length%3 != 0) { break; }
                    for(int i=0;i< wbuff.Length / 3; i++) 
                    {
                        if ((Convert.ToByte(rbuff[3 * i + 0]) % 2) == 0)
                        {
                            ////写入函数
                            /////按照IIC格式，device address，reg  address ，data进行传送。  设备地址此处兼容8805代码，从8bit缩减为7bit模式进行传输。
                            READ_ACK = CH341WriteI2C(Device_ID, Convert.ToByte(rbuff[3 * i + 0] / 2), rbuff[3 * i + 1], rbuff[3 * i + 2]);
                        }
                        else
                        {
                            ////回读函数 
                            READ_ACK = CH341ReadI2C(Device_ID, Convert.ToByte(rbuff[3 * i + 0] / 2), rbuff[3 * i + 1], read_data);
                            rbuff[3 * i + 2] =  read_data[0];
                        }
                        progressBar1.Value = i * 100 / (wbuff.Length / 3);////显示送code的进度条
                        //CH341SetDelaymS(0, 1);/////延时api无效。

                       
                    }
                    break;

                default:
                    READ_ACK = CH341StreamSPI4(Device_ID, 0x80, lenth, rbuff);
                    break;
            }
            
            //for(int i=0;i< lenth;i++)
            {
                datar.Text = byteToHexStr(rbuff);
            }
            progressBar1.Value = 100;////显示送code的进度条 100%完成；
            Message.Text = "传输完成>>>>>>>>>      ";
            countDataw.Text = "共计传输了: " + wbuff.Length / 3 + " 笔";
            //formatDataw();
        }

        private void close341_Click(object sender, EventArgs e)
        {
            CH341CloseDevice(Device_ID);
            Message.Text = "Ch341A is closed!";
            open341.Enabled = true;
            close341.Enabled = false;
            datalen.Enabled = false;
            dataw.Enabled = false;
            datar.Enabled = false;
            transport.Enabled = false;
            claerdataw.Enabled = false;
            formatdw.Enabled = false;
            cleardatar.Enabled = false;
            datalen.Enabled = false;
            Device_status = false;
            Message.Text = "close Ch341A fail!";
        }

        private void claerdataw_Click(object sender, EventArgs e)
        {
            dataw.Text = "";
        }

        private void cleardatar_Click(object sender, EventArgs e)
        {
            datar.Text = "";
        }

        private void formatDataw()
        {
            byte[] hex = strToToHexByte(dataw.Text);
            if (hex == null) return;
            //dataw.Text = byteToHexStr(hex);
            countDataw.Text = "count: " + dataw.Text.Length / 3 +" byte";
        }
        
        private void formatdw_Click(object sender, EventArgs e)
        {
            //formatDataw();
            //if (IC_comboBox.SelectedIndex == Setting.IC_Type.NT37700C)
            {
                if (Child_Gamma_Window_Open_Enable == true)
                {
                    eDP_Setting_Form = new eDP_Setting(this);
                    eDP_Setting_Form.Show();
                }
                else
                {
                    if (Child_window_hide_already == false)
                    {
                        eDP_Setting_Form.Hide();
                    }
                    else
                    {
                        eDP_Setting_Form.Show();
                    }
                }
            }
        }

        private void about_Click(object sender, EventArgs e)
        {
            MessageBox.Show(
                "**********************************"+ "\r\n" +
                "Alan_cheng     " +"\r\n"+
                "@ https://gitee.com/Alancheng86"+ "\r\n"+
                "444656575@qq.com"+"\r\n"+
                "**********************************");
        }


    }
}
